package com.dick.weixin.service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import net.sf.json.JSONObject;

import com.dick.weixin.pojo.WeixinQRCode;
import com.dick.weixin.util.CommonUtil;
import com.dick.weixin.util.logging.Logger;
import com.dick.weixin.util.logging.LoggerFactory;

/**
 * 微信码操作类 类 名 称： QRCode 类 描 述： 创 建 人： zhangyaomin 邮 箱：zhangyaomin@yunchuangyi.cn
 * 创建时间：2014-3-11上午11:19:08
 */
public class WeixinQRCodeService {

	private static Logger log = LoggerFactory
			.getLogger(WeixinQRCodeService.class);

	/**
	 * 创建临时带参数二维码
	 * 
	 * @param accessToken
	 *            接口访问凭证
	 * @param expireSeconds
	 *            二维码码有效时间，单位为秒，最长为1800秒
	 * @param sceneId
	 *            场景ID
	 * @return
	 */
	public static WeixinQRCode createTemporaryQRCode(String accessToken,
			int expireSeconds, int sceneId) {

		WeixinQRCode weixinQRCode = null;
		// 拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESS_TOKEN";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
		// 需要提交的JSON数据
		String jsonMsg = "{\"expire_seconds\":%d,\"action_name\":\"QR_SCENE\",\"action_info\":{\"scene\":{\"scene_id\":%d}}}";
		JSONObject jsonObject = CommonUtil.httpRequest(requestUrl, "POST",
				String.format(jsonMsg, expireSeconds, sceneId));
		if (null != jsonObject) {
			try {
				weixinQRCode = new WeixinQRCode();
				weixinQRCode.setTicket(jsonObject.getString("ticket"));
				weixinQRCode.setExpireSecondes(jsonObject
						.getInt("expire_seconds"));
				log.info("创建临时带参二维码成功 ticket:{} expire_second:{}", weixinQRCode
						.getTicket()
						+ "", weixinQRCode.getExpireSecondes() + "");
			} catch (Exception e) {
				weixinQRCode = null;
				int errorCode = jsonObject.getInt("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				log.error("创建临时带参二维码失败 errcode:{} errmsg:{}", errorCode + "",
						errorMsg);
				e.printStackTrace();
			}

		}
		return weixinQRCode;
	}

	/**
	 * 创建永久带参二维码
	 * 
	 * @param accessToken
	 *            接口访问凭证
	 * @param sceneId
	 *            场景ID
	 * @return
	 */
	public static String createPermanentQRCode(String accessToken, int sceneId) {
		String ticket = null;
		// 拼接请求地址
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=ACCESS_TOKEN";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
		// 需要提交的JSON数据
		String jsonMsg = "{\"action_name\":\"QR_LIMIT_SCENE\",\"action_info\":{\"scene\":{\"scene_id\":%d}}}";
		JSONObject jsonObject = CommonUtil.httpRequest(requestUrl, "POST",
				String.format(jsonMsg, sceneId));
		if (null != jsonObject) {
			try {
				ticket = jsonObject.getString("ticket");
				log.info("创建永久带参二维码成功 ticket:{}", ticket);
			} catch (Exception e) {
				int errorCode = jsonObject.getInt("errcode");
				String errorMsg = jsonObject.getString("errmsg");
				log.error("创建永久带参二维码失败 errcode:{} errmsg:{}", errorCode + "",
						errorMsg);
				e.printStackTrace();
			}

		}
		return ticket;
	}

	/**
	 * 根据ticket获取二维码
	 * 
	 * @param ticket
	 *            二维码ticket
	 * @param savePath
	 *            保存路径
	 * @return
	 */
	public static String getQRCode(String ticket, String savePath) {
		String filePath = null;
		// 拼接请求地址
		String requestUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
		requestUrl = requestUrl.replace("TICKET", CommonUtil
				.urlEncodeUTF8(ticket));
		try {
			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			if (!savePath.endsWith("/"))
				savePath += "/";
			// 将ticket作为文件名
			filePath = savePath + ticket + ".jpg";
			// 将微信服务器返回的输入流写入文件
			BufferedInputStream bis = new BufferedInputStream(conn
					.getInputStream());
			FileOutputStream fos = new FileOutputStream(new File(filePath));

			byte[] buf = new byte[8096];
			int size = 0;
			while ((size = bis.read(buf)) != -1)
				fos.write(buf, 0, size);
			fos.close();
			bis.close();
			conn.disconnect();
			log.info("根据ticket换取二维码成功，filePath=" + filePath);

		} catch (Exception e) {
			filePath = null;
			log.error("根据ticket换取二维码失败：{}", e);
		}
		return filePath;
	}

	public static void main(String[] args) {
		// 获取接口访问凭证
		String accessToken = CommonUtil.getToken("appid", "appsecret")
				.getAccessToken();
		// 创建临时二维码
		// WeixinQRCode weixinQRCode = createTemporaryQRCode(accessToken, 900,
		// 111111);
		// System.out.println(weixinQRCode.getTicket() + "*****"
		// + weixinQRCode.getExpireSecondes());
		// 创建永久带参二维码
		String ticket = createPermanentQRCode(accessToken, 617);
		String savePath = "/tmp";
		getQRCode(ticket, savePath);
		System.out.println(ticket);
	}

}
